package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.WemediaConstants;
import com.heima.common.exception.CostumExcepition;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.MyThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 查询文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        //1.检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        Integer channelId = dto.getChannelId();
        if(channelId!=null){
            wrapper.eq(WmNews::getChannelId,channelId);
        }

        Date beginPubDate = dto.getBeginPubDate();
        Date endPubDate = dto.getEndPubDate();
        if(beginPubDate!=null||endPubDate!=null){
            wrapper.in(WmNews::getCreatedTime,beginPubDate,endPubDate);
        }

        String keyword = dto.getKeyword();
        if(StringUtils.isNotEmpty(keyword)){
            wrapper.like(WmNews::getTitle,keyword);
        }

        Short status = dto.getStatus();
        if(status!=null){
            wrapper.eq(WmNews::getStatus,status);
        }

        Integer user = MyThreadLocal.getUser().getId();
        //指定当前用户
        wrapper.eq(WmNews::getUserId,user);

        wrapper.orderByDesc(WmNews::getCreatedTime);

        //查询
        Page<WmNews> page = page(new Page<>(dto.getPage(), dto.getSize()), wrapper);



        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 新增文章
     *
     * @param newsDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult add(WmNewsDto newsDto) throws Exception {

        //0.条件判断
        if(newsDto == null || newsDto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.保存或修改文章

        //创建news对象拷贝共有属性
        WmNews news = new WmNews();
        BeanUtils.copyProperties(newsDto,news);
        //保存图片字符串
        if(newsDto.getImages().size()>0&&newsDto.getImages()!=null){
            news.setImages(StringUtils.join(newsDto.getImages(),","));
        }
        //创建时间
        news.setCreatedTime(new Date());

        news.setUserId(MyThreadLocal.getUser().getId());

        //提取内容images集合
        List<String> images = getImages(newsDto.getContent());
        //保存封面与news的关系
        List<String> dtoImages = newsDto.getImages();

        //类型为自动对dtoimages,type重新赋值
        if(newsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //类型为自动,设置type及images属性
            if(images.size() >= 3){
                news.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                dtoImages = images.stream().distinct().limit(3).collect(Collectors.toList());
            }else if(images.size() >= 1 ){
                //单图
                news.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                dtoImages = images.stream().distinct().limit(1).collect(Collectors.toList());
            }else {
                //无图
                news.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }

        saveOrUpdateNews(news);

        //如果存入草稿,不用保存素材
        if(newsDto.getStatus().equals(WmNews.Status.NORMAL)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //保存news与materials的关系
        saveMaterialsAndNews(news.getId(),images,WemediaConstants.WM_CONTENT_REFERENCE);

        saveMaterialsAndNews(news.getId(),dtoImages,WemediaConstants.WM_COVER_REFERENCE);

        wmNewsAutoScanService.autoScanWmNews(news.getId());

        return ResponseResult.okResult("操作成功");
    }

    //保存或者新增
    private void saveOrUpdateNews(WmNews news) {
//补全属性
        news.setUserId(MyThreadLocal.getUser().getId());
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        news.setEnable((short)1);//默认上架
        log.info("{}",news);
        Integer id = news.getId();
        if(id==null){
            //新增
            save(news);
        }else {
            //修改
             //删除素材关联
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,id));
            updateById(news);
        }
    }

    //保存素材与文章关系
    private void saveMaterialsAndNews(Integer id, List<String> images,int type) {

        if (images.size()!=0){

            //内容图片去重
            images=  images.stream().distinct().collect(Collectors.toList());
            //查询素材ids
            LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<WmMaterial>();
            wrapper.in(WmMaterial::getUrl,images).eq(WmMaterial::getUserId,MyThreadLocal.getUser().getId());
            List<WmMaterial> list = wmMaterialMapper.selectList(wrapper);
            List<Integer> idList = list.stream().map(WmMaterial::getId).collect(Collectors.toList());

            if(list.size()!=images.size()||list.size()==0) {
                throw new CostumExcepition(AppHttpCodeEnum.PARAM_INVALID);
            }
            //提交保存
            wmNewsMaterialMapper.saveRelations(idList,id,(short)type);
        }



    }


    //从数组中提取图片信息
    private List<String> getImages(String s) {

        List<Map> maps = JSON.parseArray(s, Map.class);
        List<String> set = new ArrayList<>();
        for(Map map:maps){

            if(map.get("type").equals("image")){
                set.add((String) map.get("value"));
            }
        }


        return set;
    }

    //LTAI5tJueEFBobqhYEB8sbi8
    //Bsi1hgof2orENa5qzGEoCmWamKcKBe

}